package hservice

import (
	// "encoding/json"
	// "fmt"
	"sync"
	"time"

	"advertoper/db"
	"advertoper/errorcode"

	"doubimeizhi.com/datatable"
	"doubimeizhi.com/utility"

	log "github.com/cihub/seelog"
)

var (
	defaultZJPictureInfoService *ZJPictureInfoService
)

type ZJPictureInfoService struct {
	zjPictureinfo map[int]*ZJPictureItem
	zjPictureLock *sync.RWMutex
	PictureMaxId  int
}

func newZJPictureInfoService() *ZJPictureInfoService {
	service := &ZJPictureInfoService{}
	service.zjPictureinfo = make(map[int]*ZJPictureItem)
	service.zjPictureLock = new(sync.RWMutex)
	service.PictureMaxId = 0
	service.loadDataInit() //load数据
	return service
}

func GetZJPictureInfoService() *ZJPictureInfoService {
	if defaultZJPictureInfoService == nil {
		defaultZJPictureInfoService = newZJPictureInfoService()
	}
	return defaultZJPictureInfoService
}

//添加
type ZJPictureAdd struct {
	RegionCode string `json:"region_code"`
	StartTick  int64  `json:"starttick"`
	EndTick    int64  `json:"endtick"`
	PicUrl     string `json:"pic_url"`
	Size       string `json:"size"`
}

//修改
type ZJPictureUpdate struct {
	ZJPictureAdd
	Id     int `json:"id"`
	Status int `json:"status"`
}

//缓存数据
type ZJPictureItem struct {
	ZJPictureUpdate
	InsertTick int64 `json:"insert_tick"`
	UpdateTick int64 `json:"update_tick"`
}

//查询list
type ZJPictureList struct {
	Id         int    `json:"id"`
	Status     int    `json:"status"`
	RegionCode string `json:"region_code"`
	StartTick  string `json:"starttick"` //展示的时候展示字符串时间
	EndTick    string `json:"endtick"`   //展示的时候展示字符串时间
	InsertTime string `json:"insert_time"`
	UpdateTime string `json:"update_time"`
	PicUrl     string `json:"pic_url"`
	Size       string `json:"size"`
}

//客户端查（加上id）
type ZJPictureUserList struct {
	Id     int    `json:"id"`
	PicUrl string `json:"pic_url"`
	Size   string `json:"size"`
}

//load数据缓存
func (p *ZJPictureInfoService) loadDataInit() {
	daq := datatable.NewDataTableQuery()
	daq.SetTableName("zjpicture")
	daq.PushField(&datatable.FiledItem{Alias: "id", Field: "id"})
	daq.PushField(&datatable.FiledItem{Alias: "region_code", Field: "region_code"})
	daq.PushField(&datatable.FiledItem{Alias: "size", Field: "size"})
	daq.PushField(&datatable.FiledItem{Alias: "pic_url", Field: "pic_url"})
	daq.PushField(&datatable.FiledItem{Alias: "starttick", Field: "starttick"})
	daq.PushField(&datatable.FiledItem{Alias: "endtick", Field: "endtick"})
	daq.PushField(&datatable.FiledItem{Alias: "insert_tick", Field: "insert_tick"})
	daq.PushField(&datatable.FiledItem{Alias: "update_tick", Field: "update_tick"})
	daq.PushField(&datatable.FiledItem{Alias: "status", Field: "status"})
	sql, values := daq.GenerateSQL()
	mysqlHelper := db.GetHomePageInfoMysqlHelper()
	results, err := mysqlHelper.Query(sql, values...)
	if err != nil {
		log.Errorf("load all Picture data fail ,~~~init(),err is %s", err.Error())
		return
	}
	p.zjPictureLock.Lock()
	defer p.zjPictureLock.Unlock()
	for _, dt := range results {
		item := &ZJPictureItem{}
		item.Id = mysqlHelper.GetColInt(dt, "id")
		item.RegionCode = mysqlHelper.GetColString(dt, "region_code")
		item.Size = mysqlHelper.GetColString(dt, "size")
		item.PicUrl = mysqlHelper.GetColString(dt, "pic_url")
		item.StartTick = mysqlHelper.GetColInt64(dt, "starttick")
		item.EndTick = mysqlHelper.GetColInt64(dt, "endtick")
		item.InsertTick = mysqlHelper.GetColInt64(dt, "insert_tick")
		item.UpdateTick = mysqlHelper.GetColInt64(dt, "update_tick")
		item.Status = mysqlHelper.GetColInt(dt, "status")

		if item.Id > p.PictureMaxId {
			p.PictureMaxId = item.Id
		}
		//加入缓存
		p.zjPictureinfo[item.Id] = item
	}
	log.Infof("load zjPicture data,len is :%d", len(p.zjPictureinfo))
}

//添加数据
func (p *ZJPictureInfoService) PictureAdd(req *ZJPictureAdd) (uint, string) {
	if req.EndTick < req.StartTick {
		return 1002, "失效时间不能小于开始有效时间"
	}
	p.zjPictureLock.Lock()
	defer p.zjPictureLock.Unlock()
	//保存
	nowTime := time.Now().Unix()
	p.PictureMaxId += 1

	data := make(map[string]*utility.MySQLFieldValue)
	data["id"] = utility.NewMySQLFieldValue(p.PictureMaxId, false)
	data["region_code"] = utility.NewMySQLFieldValue(req.RegionCode, false)
	data["size"] = utility.NewMySQLFieldValue(req.Size, false)
	data["pic_url"] = utility.NewMySQLFieldValue(req.PicUrl, false)
	data["starttick"] = utility.NewMySQLFieldValue(req.StartTick, false)
	data["endtick"] = utility.NewMySQLFieldValue(req.EndTick, false)
	data["insert_tick"] = utility.NewMySQLFieldValue(nowTime, false)
	data["update_tick"] = utility.NewMySQLFieldValue(nowTime, false)
	mysqlHelper := db.GetHomePageInfoMysqlHelper()
	_, err := mysqlHelper.SaveRecord(data, "zjpicture")
	if err != nil {
		log.Errorf("insert Picture fail ,~~~PictureAdd,err is %s", err.Error())
		return errorcode.EC_GL_INTERNAL_ERROR, errorcode.Msg(errorcode.EC_GL_INTERNAL_ERROR)
	}
	//添加缓存
	item := &ZJPictureItem{}
	item.Id = p.PictureMaxId
	item.RegionCode = req.RegionCode
	item.Size = req.Size
	item.PicUrl = req.PicUrl
	item.StartTick = req.StartTick
	item.EndTick = req.EndTick
	item.InsertTick = nowTime
	item.UpdateTick = nowTime
	item.Status = 1

	p.zjPictureinfo[p.PictureMaxId] = item

	return errorcode.EC_GL_SUCCESS, errorcode.Msg(errorcode.EC_GL_SUCCESS)
}

//修改数据
func (p *ZJPictureInfoService) PictureUpdate(req *ZJPictureUpdate) (uint, string) {
	//获取缓存数据
	oldData, ok := p.zjPictureinfo[req.Id]
	if !ok {
		return 101, "row is not invalid"
	}
	currDate := &ZJPictureItem{}
	//将老的数据copy一份
	currDate.Id = oldData.Id
	currDate.EndTick = oldData.EndTick
	currDate.InsertTick = oldData.InsertTick
	currDate.PicUrl = oldData.PicUrl
	currDate.RegionCode = oldData.RegionCode
	currDate.StartTick = oldData.StartTick
	currDate.Status = oldData.Status
	currDate.Size = oldData.Size
	currDate.UpdateTick = oldData.UpdateTick

	updaq := datatable.NewDataTableUpdate()
	updaq.SetTableName("zjpicture")

	if req.RegionCode != "" {
		updaq.SetUpdateValue("region_code=?", req.RegionCode)
		currDate.RegionCode = req.RegionCode
	}
	if req.PicUrl != "" {
		updaq.SetUpdateValue("pic_url=?", req.PicUrl)
		currDate.PicUrl = req.PicUrl
	}
	if req.Size != "" {
		updaq.SetUpdateValue("size=?", req.Size)
		currDate.Size = req.Size
	}
	if req.StartTick != 0 {
		updaq.SetUpdateValue("starttick=?", req.StartTick)
		currDate.StartTick = req.StartTick
	}
	if req.EndTick != 0 {
		updaq.SetUpdateValue("endtick=?", req.EndTick)
		currDate.EndTick = req.EndTick
	}
	if req.Status != 0 {
		if req.Status != 1 && req.Status != -1 {
			req.Status = 1
		}
		updaq.SetUpdateValue("status=?", req.Status)
		currDate.Status = req.Status
	}

	nowTime := time.Now().Unix()
	updaq.SetUpdateValue("update_tick=?", nowTime)
	currDate.UpdateTick = nowTime

	updaq.PushCondition("id=?", req.Id)

	sql, values := updaq.GenerateSQL()
	mysqlHelper := db.GetHomePageInfoMysqlHelper()
	_, err := mysqlHelper.Exec(sql, values...)
	if err != nil {
		log.Errorf("update Picture fail ,~~~PictureUpdate,err is %s", err.Error())
		return errorcode.EC_GL_INTERNAL_ERROR, errorcode.Msg(errorcode.EC_GL_INTERNAL_ERROR)
	}
	//更新缓存
	p.zjPictureinfo[req.Id] = currDate

	return errorcode.EC_GL_SUCCESS, errorcode.Msg(errorcode.EC_GL_SUCCESS)
}

//web查询数据
func (p *ZJPictureInfoService) PictureList(status int) []*ZJPictureList {
	if status != 1 && status != -1 {
		status = 1
	}
	data := make([]*ZJPictureList, 0)
	//遍历缓存取数据
	for _, value := range p.zjPictureinfo {
		item := &ZJPictureList{}
		if value.Status == status {
			item.Id = value.Id
			item.PicUrl = value.PicUrl
			item.RegionCode = value.RegionCode
			item.Status = value.Status
			item.Size = value.Size
			item.InsertTime = time.Unix(value.InsertTick, 0).Format("2006-01-02 15:04:05")
			item.UpdateTime = time.Unix(value.UpdateTick, 0).Format("2006-01-02 15:04:05")
			item.StartTick = time.Unix(value.StartTick, 0).Format("2006-01-02 15:04:05")
			item.EndTick = time.Unix(value.EndTick, 0).Format("2006-01-02 15:04:05")

			data = append(data, item)
		}
	}
	return data
}

//客户端查询数据
func (p *ZJPictureInfoService) UserGetPictureList(ids []int, regionCode string) []*ZJPictureUserList {
	data := make([]*ZJPictureUserList, 0)
	//遍历找到满足id的数据
	for _, dt := range ids {
		for key, value := range p.zjPictureinfo {
			if key == dt {
				//当id满足，再过滤掉不在有效期的数据
				nowtick := time.Now().Unix()
				if value.StartTick <= nowtick && value.EndTick >= nowtick && value.Status == 1 &&
					IsRegionCode(value.RegionCode, regionCode) {
					item := &ZJPictureUserList{}
					item.Id = value.Id
					item.PicUrl = value.PicUrl
					item.Size = value.Size

					data = append(data, item)
				}
			}
		}
	}
	return data

}
